/*
 * @Author: your name
 * @Date: 2022-04-25 09:41:54
 * @LastEditTime: 2022-04-26 10:28:14
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \mallAdmin\src\app\main\used-store\used-marketing-manage\components\goods-select-modal\goods-select-modal.component.ts
 */
import { Component, OnInit, Input, EventEmitter, ViewChild, forwardRef, Output  } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';

import { sencondStatusOptions } from '../../used-marketing-manage.pipe';
import { CommonService } from '../../../../../services-common/common.service';
import { SecondCouponService } from '../../services/second-coupon.service';

@Component({
  selector: 'goods-select-modal',
  templateUrl: './goods-select-modal.component.html',
  styleUrls: ['./goods-select-modal.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => GoodsSelectModalComponent),
      multi: true
    }
  ]
})
export class GoodsSelectModalComponent implements ControlValueAccessor, OnInit {

  @Input() tickOptions!: Array<any>; // 勾选项
  @Input() disabledOptions: Array<any> = []; // 禁选项
  @Output() subOptions = new EventEmitter();

  userTypeOptions = [
    {value: 0, label: '不限'},
    {value: 1, label: 'C端'},
    {value: 2, label: 'B端'}
  ]; // 适用用户Options
  statusOptions: any = []; // 状态Options
  brandOptions = []; // 设备品牌Options
  modelOptions = []; // 设备型号Options
  locationOptions = []; // 库位Options
  conditionOptionsB = []; // B端成色Options
  conditionOptionsC = []; // C端成色Options

  searchOptions = [
    { type: 1, labelText: '编码', valueKey: 'equipmentCode', value: '' },
    {
      type: 2,
      labelText: '设备品牌',
      valueKey: 'typeId',
      value: [],
      multiple: true,
      selectBindKey: {key: 'id', label: 'name'},
      selectOptions: [],
      selectChange: (val: any) => {
        this.brandChange(val)
      }
    },{
      type: 2,
      labelText: '设备型号',
      valueKey: 'modelId',
      value: [],
      multiple: true,
      selectBindKey: {key: 'id', label: 'name'},
      selectOptions: [],
      hide: true
    },{
      type: 2,
      labelText: '状态',
      valueKey: 'status',
      value: [],
      multiple: true,
      selectOptions: []
    },{
      type: 2,
      labelText: '适用用户',
      valueKey: 'userType',
      value: [],
      multiple: true,
      selectOptions: [...this.userTypeOptions],
    },{
      type: 2,
      labelText: '库位',
      valueKey: 'libraryId',
      value: [],
      multiple: true,
      selectBindKey: {key: 'id', label: 'name'},
      selectOptions: [],
    },{
      type: 2,
      labelText: 'B端成色',
      valueKey: 'colourIdB',
      value: [],
      multiple: true,
      selectBindKey: {key: 'id', label: 'name'},
      selectOptions: [],
    },{
      type: 2,
      labelText: 'C端成色',
      valueKey: 'colourId',
      value: [],
      multiple: true,
      selectBindKey: {key: 'id', label: 'name'},
      selectOptions: [],
    },
    { type: 3, labelText: '成交入库时间', valueKey: ['clinchTime', 'clinchEndTime'], value: [], isTimeSelect: true }
  ];
  searchParams: any = {};
  
  tableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 10,
    total: 0
  };

  isVisible = false;
  _onChange: any = () => {};
  
  // Table Check
  checked = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = [];
  setOfCheckedId = new Set<number>();
  setOfCheckedArrs: any[] = [];

  constructor(
    private message: NzMessageService,
    private commonService: CommonService,
    private services: SecondCouponService
  ) { }

  ngOnInit(): void {
  }

  // Search Options Set Value
  searchSetup(keyStr: string, options: any) {
    let objIndex = this.searchOptions.findIndex((item: any) => item.valueKey === keyStr);
    this.searchOptions[objIndex].selectOptions = options || [];
  }

  /**
   * search datas
   * ----------------------------------------------------------------
   */
  init() {
    this.statusOptions = sencondStatusOptions.filter((item: any) => item.value !== 2);
    this.searchSetup('status', this.statusOptions);
    
    this.getBrandListData();
    this.getLocationListData();
    this.conditionDatas();
    // this.loadTable();
  }

  // 设备品牌 Options
  async getBrandListData() {
    let params = {
      page: 1,
      pageSize: 9999
    }
    const res: any = await this.services.getBrandList(params);
    const { records } = res.data || {};
    this.brandOptions = records || [];
    this.searchSetup('typeId', records);
  }

  // 品牌Select Change
  brandChange(val: any) {
    let objIndex = this.searchOptions.findIndex((item: any) => item.valueKey === 'modelId');
    if (val !== '') {
      let ids = val.join(',');
      this.getModelListData(ids);
      this.searchOptions[objIndex].hide = false;
    } else {
      this.searchOptions[objIndex].hide = true;
      this.searchSetup('modelId', []);
    }
  }

  // 设备型号 Options
  async getModelListData(brandId: string) {
    let params = {
      brandId: brandId,
      page: 1,
      pageSize: 9999
    }
    const res: any = await this.services.getModelList(params);
    const { records } = res.data || {};
    this.modelOptions = records || [];
    this.searchSetup('modelId', records);
  }

  // 库位 Options
  async getLocationListData() {
    let params = {
      page: 1,
      pageSize: 9999
    }
    const res: any = await this.services.getLocationList(params);
    const { records } = res.data || {};
    this.locationOptions = records || [];
    this.searchSetup('libraryId', records);
  }

  // 成色
  async conditionDatas() {
    this.conditionOptionsB = await this.commonService.getDictList('machine_condition_b');
    this.conditionOptionsC = await this.commonService.getDictList('machine_condition');
    this.searchSetup('colourIdB', this.conditionOptionsB);
    this.searchSetup('colourId', this.conditionOptionsC);
  }

  /**
   * Table 状态 !== 已售出
   * ----------------------------------------------------------------
   */
  async loadTable() {
    let params = {
      ...this.searchParams,
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.loading = true;
    const res: any = await this.services.getGoodsList(params);
    this.tableParams.loading = false;
    
    if (res.code === 0) {
      const { records, total } = res.data || {};
      this.tableParams.tableData = records || [];
      this.tableParams.total = total || 0; 
    } else {
      this.message.error(res.message);
    }
  }

  // 查询
  queryData(params: any) {
    this.searchParams = params;

    // 状态 !== 已售出
    if (!this.searchParams.status) {
      this.searchParams.status = this.statusOptions.map((item: any) => item.value).join(',');
    }

    this.tableParams.page = 1;
    this.loadTable();
  }

  // 重置
  resetData(params: any) {
    let objIndex = this.searchOptions.findIndex((item: any) => item.valueKey === 'modelId');
    this.searchOptions[objIndex].hide = true;
    this.searchSetup('modelId', []);

    // 状态 !== 已售出
    if (!this.searchParams.status) {
      this.searchParams.status = this.statusOptions.map((item: any) => item.value).join(',');
    }

    this.searchParams = params;
    this.tableParams.page = 1;
    this.loadTable();
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }
  
  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  // 关联提交
  relationOption() {
    if (!this.setOfCheckedId.size) {
      this.message.warning('请先勾选所需关联项');
      return
    }
    this.subOptions.emit({
      ids: [...this.setOfCheckedId],
      tableDatas: this.setOfCheckedArrs
    })
    this.handleCancel();
  }

  /**
   * Table Check
   * ----------------------------------------------------------------
   */
  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);

      let obj = this.listOfCurrentPageData.find((item: any) => item.id === id);
      this.setOfCheckedArrs.push(obj);
    } else {
      this.setOfCheckedId.delete(id);

      let delIndex = this.setOfCheckedArrs.findIndex((item: any) => item.id === id);
      this.setOfCheckedArrs.splice(delIndex, 1);
    }
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(value: boolean): void {
    this.listOfCurrentPageData.filter((tag: any) => !this.disabledOptions.includes(tag.id)).forEach(item => this.updateCheckedSet(item.id, value));
    this.refreshCheckedStatus();
  }

  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    this.checked = this.listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.id));
    this.indeterminate = this.listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }

  /**
   * ngModel isVisible
   * ----------------------------------------------------------------
   */
  handleCancel() {
    this.setOfCheckedId.clear();
    this.setOfCheckedArrs = [];
    this.isVisible = false;
    this._onChange(this.isVisible);
  }

  writeValue(val: any) {
    // isVisible Modal Open
    if (val) {
      this.disabledOptions = this.disabledOptions.map((m: any) => +m);
      let arrs = this.tickOptions.length ? this.tickOptions.map((m: any) => +m) : [];
      this.setOfCheckedId = new Set(arrs);
      this.init();
    }
    this.isVisible = val;
  }

  registerOnChange(fn: (_: any) => void): void {
    this._onChange = fn;
  }

  registerOnTouched(fn: any): void {}
}
